<template>
  <div>
    <SearchBar @query="queryList" @swit="switClick" />
    <a-card class="mt-2">
      <div class="flex justify-between items-center pb-4">
        <a-space>
          <BaseButton type="primary" debounce :disabled="!selectedRowKeys.length" @click="onDistributeDrug"> 发药 </BaseButton>
          <a-button type="primary" @click="onPrint"> 针剂发药单 </a-button>
          <a-button>导出</a-button>
          <span v-if="selectedRowKeys.length">
            {{ `已选 ${selectedRowKeys.length} 项` }}
          </span>
        </a-space>
      </div>

      <BaseTable
        v-if="!swit"
        column-code="00001035"
        :loading="loading"
        :data-source="tableData"
        bordered
        fill
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'advExecType'">
            <!-- 0：临时 1：长期 2：出院带药" -->
            <span v-if="record.advExecType === '0'">临时</span>
            <span v-else-if="record.advExecType === '1'">长期</span>
            <span v-else-if="record.advExecType === '2'">出院带药</span>
            <span v-else>-</span>
          </template>
          <template v-if="column.dataIndex === 'advName'">
            <MedicineInfo
              :value="{
                mc: record?.advName,
                gg: record?.gg,
                jl: record?.clinicalDose + record?.clinicalDoseUnit,
                cj: record?.cj,
                yf: record?.deliverRoute?.fyff,
                pl: record?.fqy?.pl,
                gg: record?.spc,
                insureStatus: record?.insureStatus,
                skinTestFlag: record?.skinTestFlag
              }"
            />
          </template>
          <template v-if="column.dataIndex === 'brName'">
            <span>{{ record.brName }}</span>
            <span class="ml-4">{{ record.brXb }}</span>
            <span class="ml-4">{{ record.brAge }}</span>
          </template>
        </template>
      </BaseTable>
      <BaseTable
        v-else
        column-code="00001034"
        :loading="loading"
        fill
        row-key="advCode"
        :data-source="tableData"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'advName'">
            <MedicineInfo
              :value="{
                mc: record?.advName,
                gg: record?.gg,
                jl: record?.clinicalDose + record?.clinicalDoseUnit,
                cj: record?.cj,
                yf: record?.deliverRoute?.fyff,
                pl: record?.fqy?.pl,
                gg: record?.spc,
                insureStatus: record?.insureStatus,
                skinTestFlag: record?.skinTestFlag
              }"
            />
          </template>
        </template>
      </BaseTable>
    </a-card>
    <!-- <div class="absolute bottom-0 z-50 p-4 shadow-2xl bg-white"> -->
    <div class="absolute -top-[9999px]">
      <a-button ref="printRef" v-print="{ id: 'printDom' }" type="primary">打印</a-button>
      <PrintView id="printDom" :print-data="printData" :print-type="printType" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import SearchBar from '../components/SearchBar'
import PrintView from './PrintView'

const printRef = ref(null)
const printData = ref([])
const printType = ref('0')
const loading = ref(false)
const selectedRowKeys = ref([])
const selectedRowData = ref([])
const tableData = ref([])
const formStates = ref({})
const swit = ref(true)
const WardName = ref('')
const queryList = async (formState) => {
  formStates.value = formState.value
  selectedRowKeys.value = ''
  loading.value = true
  WardName.value = formStates.value.wardname
  const { code, data } = await post('/inp/zyyf/getDistributeDrugList', {
    wardId: formStates.value.bqbh,
    chkZJ: swit.value ? '1' : '0',
    eddate: formStates.value['dateRange']?.[1],
    stdate: formStates.value['dateRange']?.[0],
    yjlx: '0',
    zjm: swit.value ? undefined : formStates.value.pyjm,
    ypzjm: swit.value ? formStates.value.pyjm : undefined,
    bedCode: swit.value ? undefined : formStates.value.bedCode,
    drugStoreId: formStates.value?.drugStoreId
  })
  loading.value = false
  if (code !== 0) return
  tableData.value = data
}
const switClick = (e) => {
  swit.value = e === '1' ? true : false
  tableData.value = []
  queryList(formStates)
  selectedRowKeys.value = []
}
const onDistributeDrug = async () => {
  if (!formStates.value?.drugStoreId) return message.error('请选择发药药房')
  if (!formStates.value?.shr) return message.error('请选择审核人')
  if (selectedRowData.value.length <= 0) {
    message.error('请勾选需要发的药品')
    return
  }
  const p = {
    cbobqmc: WardName.value,
    chkZJ: swit.value ? '1' : '0',
    mxlist: selectedRowData.value,
    drugStoreId: formStates.value?.drugStoreId,
    shr: formStates.value?.shr,
    wardId: formStates.value.bqbh,
    distributeDrugRequest: formStates.value
  }
  const res = await post('inp/zyyf/doDistributeDrug', p)
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg)
  queryList(formStates)
}
const onSelectChange = (keys, obj) => {
  selectedRowData.value = obj
  selectedRowKeys.value = keys
}

const onPrint = async () => {
  if (!formStates.value?.shr) return message.error('请选择审核人')
  const { code, msg, data } = await post('/inp/Print/inpDispensingMedicinesPrint', {
    wardId: formStates.value.bqbh,
    chkZJ: swit.value ? '1' : '0',
    // cywfy: '1',
    eddate: formStates.value['dateRange']?.[1],
    stdate: formStates.value['dateRange']?.[0],
    yjlx: '0',
    zjm: formStates.value.pyjm,
    fyshr: formStates.value?.shr
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printType.value = swit.value ? '0' : '1'
    printData.value = JSON.parse(data)
    if (!printData.value.printData.detail?.length) return message.error('没有需要打印的数据')
    setTimeout(() => {
      printRef.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
</script>
